package com.ssyt.lms.sys.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.ssyt.lms.common.controller.BaseController;
import com.ssyt.lms.entity.RightInfo;
import com.ssyt.lms.sys.constant.SystemConstant;
import com.ssyt.lms.sys.entity.ChildrenMenu;
import com.ssyt.lms.sys.entity.MenuItem;
import com.ssyt.lms.sys.service.IInitSystemService;

/**
 * 初始化系统基本操作的控制器类
 * @author Administrator
 * @since 2016年5月25日
 */

@Controller
@RequestMapping("/init")
public class InitSystemController extends BaseController implements SystemConstant{
	
	@Autowired
	@Qualifier("initSystemService")
	private IInitSystemService initService;
	/**
	 * 初始化登录界面的方法
	 * @return
	 */
	@RequestMapping("/loginPage")
	public String initLogin() {
		return LOGIN_PAGE;
	}
	
	/**
	 * 定义初始化主页方法
	 */
	@RequestMapping("/initIndexPage") 
	public String initIndexPage(HttpServletRequest request) {
		
		// 获取当前登录用户所有主菜单
		List<RightInfo> rightList = initService.getMainMenuByRoleId(getCurrentUser(request));
		// 把所有主菜单保存到request对象中
		request.setAttribute("rightList", rightList);
		
		// 定义一个存储ChildrenMenu对象的集合
		List<ChildrenMenu> childrenMenuList = new ArrayList<ChildrenMenu>();
		
		// 循环获取主菜单下面对应子菜单
		if (null!=rightList && rightList.size()>0) {
			for (RightInfo right : rightList) {
				// 获取当前遍历主菜单下面所有的子菜单集合
				String url = request.getContextPath()+"/";
				List<RightInfo> childrenMenus = initService.getChildrenMenuByParentId(right,url);
				
				// 创建一个ChildrenMenu对象
				ChildrenMenu childrenMenu = new ChildrenMenu();
				childrenMenu.setId(right.getId());
				
				List<MenuItem> menuItems = new ArrayList<MenuItem>();
				// 创建MenuItem对象
				MenuItem menuItem = new MenuItem();
				menuItem.setText(right.getText());
				menuItem.setItems(childrenMenus);
				menuItems.add(menuItem);
				
				childrenMenu.setMenu(menuItems);
				
				childrenMenuList.add(childrenMenu);
			}
		}
		String childrenMenuJsonString = JSON.toJSONString(childrenMenuList,true);
		System.out.println(childrenMenuJsonString);
		
		// 最后把构建的json字符串保存到request对象中
		request.setAttribute("childrenJson", childrenMenuJsonString);
		
		
		return INDEX_PAGE;
	}
}
